/*
 * main.c
 *
 *  Created on: 2009-5-29
 *      Author: tian
 */
#include"mysocket.h"
int server(){
	int lsock=0;
	int rv,rsock;
	char buf[5]={0};
	struct sockaddr serv_addr;
	struct sockaddr sock_addr;
	memset(&serv_addr,0,sizeof(serv_addr));
	inet_aton("192.168.0.1",&(serv_addr.my_ip));
	printf("please input listen port:\n");
	scanf("%hu",&serv_addr.my_port);
	//serv_addr.my_port=1000;
	lsock=socket();
	if(lsock<0){
		printf("can not get socket!\n");
		return -1;
	}
	if((rv=bind(lsock,&serv_addr,sizeof(serv_addr)))<0){
		printf("can not bind!\n");
		return -1;
	}
	if((rv=listen(lsock,3))<0){
		printf("can not listen!\n");
		return -1;
	}
	printf("after listen\n");
	if((rsock=accept(lsock,&sock_addr,&rv))<0){
		printf("can not get socket!\n");
		return -1;
	}
	printf("after accept\n");
	while((rv=readfromsocket(rsock,buf,5))>0){
		printf("get:%s\n",buf);
		if(writetosocket(rsock,buf,rv)<0){
			printf("write to socket error\n");
			return -1;
		}
		memset(buf,0,5);
	}
	close(lsock);
	close(rsock);
	return 0;
}
int client(){
	int sock=socket();
	int rv;
	char buf[5]={'a',0,0,0,0};
	struct sockaddr sock_addr;
	inet_aton("192.168.0.1",&(sock_addr.peer_ip));
	inet_aton("192.168.0.2",&(sock_addr.my_ip));
	printf("please input peer_port\n");
	scanf("%hu",&sock_addr.peer_port);
	printf("please input my_port\n");
	scanf("%hu",&sock_addr.my_port);
	if(sock<0){
		printf("can not get socket!\n");
		return -1;
	}
	if((rv=connect(sock,&sock_addr,sizeof(sock_addr)))<0){
		printf("can not connect!\n");
		return -1;
	}
	printf("after connect\n");
	if((rv=writetosocket(sock,buf,1))<0){
		printf("can not get socket!\n");
		return -1;
	}
	printf("%d:after write\n",rv);
	memset(buf,0,5);
	if((rv=readfromsocket(sock,buf,5))>0){
		printf("get:%s\n",buf);
	}
	printf("%d:after read\n",rv);
	close(sock);
	return 0;
}
int main(int argc,char **argv){
	if(argc!=2){
		return -1;
	}
	if(sock_init()<0){
		printf("sock init error\n");
		return -1;
	}
	if(strcmp(argv[1],"server")==0){
		server();
	}
	if(strcmp(argv[1],"client")==0){
		client();
	}
	return 0;
}
